package _09_高频题;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/spiral-matrix/
 * @Author: haogege
 * @Date: 2021/9/3
 */
public class _54_螺旋矩阵 {

    public List<Integer> spiralOrder(int[][] matrix) {
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        List<Integer> list = new ArrayList<>();
        while (true) {
            // top-left --> top-right
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            if (++top > bottom) break;
            // top-right bottom-right
            for (int i = top; i <= bottom; i++) {
                list.add(matrix[i][right]);
            }
            if (left > --right) break;
            // bottom-right bottom-left
            if (left > right || top > bottom) break;
            for (int i = right; i >= left; i--) {
                list.add(matrix[bottom][i]);
            }
            if (top > --bottom) break;
            // bottom-left top-left
            for (int i = bottom; i >= top; i--) {
                list.add(matrix[i][left]);
            }
            if (++left > right) break;
        }
        return list;
    }

    // 定义4个指针，top, bottom, left, right
    public List<Integer> spiralOrder1(int[][] matrix) {
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        List<Integer> list = new ArrayList<>();
        while (top <= bottom && left <= right) {
            // top-left --> top-right
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            top++;
            // top-right bottom-right
            for (int i = top; i <= bottom; i++) {
                list.add(matrix[i][right]);
            }
            right--;
            // bottom-right bottom-left
            if (left > right || top > bottom) break;
            for (int i = right; i >= left; i--) {
                list.add(matrix[bottom][i]);
            }
            bottom--;
            // bottom-left top-left
            for (int i = bottom; i >= top; i--) {
                list.add(matrix[i][left]);
            }
            left++;
        }
        return list;
    }
}
